package ca.jsbr.as2js_lib.display.canvas.view 
{
	import ca.jsbr.as2js_lib.display.canvas.View;
	import ca.jsbr.as2js_lib.display.canvas.bitmap.BitmapData;
	import ca.jsbr.as2js_lib.utils.geom.Rect;
	import js.element.canvas.CanvasRenderingContext2D;
	import js.element.HTMLImageElement;
	import js.event.Event;
	/**
	 * ...
	 * @author jsbr [me@jsbr.ca]
	 */
	public class Image extends View
	{
		
		protected var _image:HTMLImageElement;
		protected var _ready:Boolean;
		protected var _bitmapData:BitmapData;
		protected var _srcHeight:Number;
		protected var _srcWidth:Number;
		protected var _alpha:Number;
		
		public function Image(src:*=null) 
		{
			_scaleX = 1;
			_scaleY = 1;
			_alpha = 1;
			addSrc(src);
		}
		
		public function addSrc(src:*):void
		{
			if (src && src.charAt)
			{
				_image = document.createElement("img");
				_image.src = src;
				_image.addEventListener("load", onLoad);
			}
			else if (src)
			{
				_image = src;
				if (_image.width == 0)
					_image.addEventListener("load", onLoad);
				else
					onLoad(null);
			}
		}
		
		protected function onLoad(e:Event):void 
		{
			_ready = true;
			if(_width==0)
				_width = _image.width;
			if(_height==0)
				_height = _image.height;
			_srcWidth = _image.width;
			_srcHeight = _image.height;
		}
		
		
		
		override public function render(ctx:CanvasRenderingContext2D):void 
		{
			if (_ready)
			{
				
				if (_bitmapData)
				{
					if (_bitmapData.isModified())
						_bitmapData.render();
					ctx.putImageData(_bitmapData.imageData, 0, 0, _srcWidth, _srcHeight, stageX, stageY, width, height);
				}
				else
					ctx.drawImage(_image, 0, 0, _srcWidth, _srcHeight, stageX, stageY, width, height);
			}
		}
		
		public function get image():HTMLImageElement 
		{
			return _image;
		}
		
		public function set image(value:HTMLImageElement):void 
		{
			_image = value;
			if (_image.width == 0)
				_image.addEventListener("load", onLoad);
			else
				onLoad(null);
		}
		
		public function get bitmapData():BitmapData 
		{
			if (!_bitmapData)
				_bitmapData = new BitmapData(_image);
			return _bitmapData;
		}
		
		public function get alpha():Number 
		{
			return _alpha;
		}
		
		public function set alpha(value:Number):void 
		{
			_alpha = value;
		}
		
	

		
		public function clone():Image
		{
			var img:Image = new Image();
			img.image = _image;
			img.x = x;
			img.y = y;
			return img;
		}
		
	}

}